import React from 'react';
import styled from 'styled-components'
import logo from './logo.svg';
import './App.css';

/**
 *
  @Get('delay')
  async prepareFileTransfer(
    @Query('id') id: string,
    @Query('delay') delay: string,
  ) {
    const timestamp = dayjs().format('mm:ss')
    await commonLib.delay(parseInt(delay))
    return ({
      id,
      timestamp,
      back: dayjs().format('mm:ss')
    });
  }
 
 */

const Wrapper = styled.div`
  font-size: 3rem;
  & p {
    color:white;
  }
  & button {
    padding: .5em;
    font-size:inherit;
  }  
`
const DELAY_MIL_SEC = [6000, 3000, 100]
const ID_LABEL = ['A', 'B', 'C']

export default function App() {
  const [data, setData] = React.useState<any>({id: '', timestamp: '', back: ''})
  const refReq = React.useRef<any>()
  const onClick = (id:number) => () => {
    if (!!refReq.current) refReq.current.abort()
    
    refReq.current = new AbortController()
    fetch(
      `http://localhost:3000/api/mock/demo/delay?id=${id}&delay=${DELAY_MIL_SEC[id]}`,
      { signal: refReq.current.signal }
    ).then((response) => {
      return response.json()
    }).then((body: any) => {
      console.log(body)
      setData({ ...body })
    }).catch((err) => {
      console.error('catch err')
      console.error(err)
    })
  }
  return (
    <div className="App">
      <header className="App-header">
        <img width={'20%'} src={logo} className="App-logox" alt="logo" />
        <Wrapper>
          { !!data?.id && 
            <p>
              <span>[ {ID_LABEL[data.id]} ]</span>
              &nbsp;&nbsp;
              <span>{data.timestamp}</span>
              &nbsp;~&nbsp;
              <span>{data.back}</span>
            </p>
          }
          { ID_LABEL.map((label:string, index:number) => (
            <button key={index} onClick={onClick(index)}>{ID_LABEL[index]}-{DELAY_MIL_SEC[index]/1000}sec</button>
          )) }
        </Wrapper>
        <div style={{height: '600px'}}>&nbsp;</div>
      </header>
    </div>
  );
}

/**
 * 
 * 
 * 
 *     if (!!ref.current) {
      console.log('abort')
      ref.current.abort()
    }
    ref.current = new AbortController()

    , { signal: ref.current.signal }
 */